package com.cgah

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import javax.servlet.http.HttpServletResponse

class UserController {

    def springSecurityService

    def index = {
        redirect(action: "create", params: params)
    }

    private Customer allow(Long currentUserId, Boolean isadmin) {
        def zid = params.id;
        // because we are allowing a user to do dis
        boolean allow = (isadmin || String.valueOf(currentUserId) == zid)
        if (!allow) {
            flash.message = "Don't make me hurt you beeyach";
        }
        return Customer.get(zid)
    }


    def create = {
        // TODO:  write the code!
        def userInstance = new User()
        userInstance.properties = params
        userInstance.enabled = true;

        return [userInstance: userInstance]
    }

    def save = {
        if (!springSecurityService.loggedIn) {
            def userInstance = new Customer(params)
            userInstance.createdDate = new Date();
            def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
            if (userInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])}"

                if (!userInstance.getAuthorities().contains(userRole)) {
                    UserRole.create(userInstance, userRole)
                }
                // log this user in afte all is said and done
                springSecurityService.reauthenticate(userInstance.username, userInstance.password);
                render(view: "regsuccessful")
            }
            else {
                render(view: "create", model: [userInstance: userInstance])
            }
        }
    }

    def edit = {
        if (springSecurityService.loggedIn) {
            def customerInstance = allow(springSecurityService.currentUser.id, SpringSecurityUtils.ifAnyGranted(Constants.ROLE_ADMIN));
            if (customerInstance) {
                if (params.version) {
                    def version = params.version.toLong()
                    if (customerInstance.version > version) {

                        customerInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'customer.label', default: 'Customer')] as Object[], "Another user has updated this Customer while you were editing")
                        render(view: "edit", model: [customerInstance: customerInstance])
                        return
                    }
                }
                customerInstance.properties = params
                if (!customerInstance.hasErrors() && customerInstance.save(flush: true)) {
                    flash.message = "Profile updated successfully"
                } else {
                    flash.message = "Error.  Profile updated failed"
                }
                redirect(action: "show", id: customerInstance.id)
            }
        } else {
            redirect(controller: "login", action: "index")
        }
    }

    def show = {
        if (springSecurityService.loggedIn) {
            def customerInstance = allow(springSecurityService.currentUser.id, SpringSecurityUtils.ifAnyGranted(Constants.ROLE_ADMIN));
            if (!customerInstance) {
                flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            }
            else {
                [customerInstance: customerInstance]
            }
        } else {
            redirect(controller: "login", action: "index")

        }
    }
}
